<?php

namespace maotool\util;

use maotool\file\FileUtil;
use maotool\object\StrUtil;
use DOMDocument;

class XmlUtil
{

    /**
     * 解码读取
     * @param $content
     * @return array
     */
    public static function toArray($content)
    {
        $content = self::clearComment($content);
        $dom = new DOMDocument('1.0', 'UTF-8');
        $dom->loadXML($content);
        $dom->hasAttributes();
        $treeHandle = function ($nodes, $treeHandle) {
            $tree = [];
            if (isset($nodes)) {
                foreach ($nodes as $childNode) {
                    $attributes = [];
                    if ($childNode->hasAttributes()) {
                        foreach ($childNode->attributes as $attribute) {
                            $attributes[$attribute->name] = $attribute->value;
                        }
                    }
                    $tree[] = [
                        "nodeName" => $childNode->nodeName,
                        "nodeValue" => $childNode->nodeValue,
                        "nodeType" => $childNode->nodeType,
                        "localName" => $childNode->localName,
                        "textContent" => $childNode->textContent,
                        "documentURI" => isset($childNode->documentURI) ? $childNode->documentURI : null,
                        "attributes" => $attributes,
                        "childNodes" => $treeHandle($childNode->childNodes, $treeHandle),
                        "childElementCount" => isset($childNode->childElementCount) ? $childNode->childElementCount : 0
                    ];
                }
            }
            return $tree;
        };
        return $treeHandle([$dom], $treeHandle);
    }

    /**
     * 去除注释
     * @param string $content
     * @return string
     */
    public static function clearComment($content)
    {
        return StrUtil::pregReplace("/<!--.*?-->/s", "", $content);
    }

}